package com.ricervcvcer.user.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ricervcvcer.common.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//当前这个类是异常处理类
@ControllerAdvice
public class RicervcvcerExceptionResolver {
    //修改
    @ExceptionHandler(value = {RuntimeException.class})
    public ModelAndView resolve(Exception exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
        return commonResolve(null, exception, request, response);
    }

    /**
     * 创建通用方法
     *
     * @param viewName  要跳转视图名称
     * @param exception 错误类型
     * @param request   请求对象
     * @param response  响应对象
     * @return 视图模型
     * @throws IOException
     */
    @Autowired
    ObjectMapper objectMapper;
    @ResponseBody
    private ModelAndView commonResolve(String viewName, Exception exception, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        // 3. 创建 ResultEntity 对象
        ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage());
        // 5. 将ResultEntity对象转换为JSON字符串
        String json = objectMapper.writeValueAsString(resultEntity);
        // 6. 将JSON字符作为响应体返回给浏览器
        response.getWriter().write(json);
        // 7. 上面已经通过原生response对象返回了响应，因此不再提供ModelAndView对象
        return null;
    }

}
